/*
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.topvision.config;

import com.topvision.utils.base.BaseConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Springfox Swagger configuration.
 * <p>
 * Warning! When having a lot of REST endpoints, Springfox can become a performance issue. In that
 * case, you can use a specific Spring profile for this class, so that only front-end developers
 * have access to the Swagger view.
 */
@Configuration
@ConditionalOnClass({ApiInfo.class, BeanValidatorPluginsConfiguration.class})
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
@Profile(BaseConstants.SPRING_PROFILE_SWAGGER)
public class SwaggerConfiguration {

    private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);

    /**
     * Swagger Springfox configuration.
     *
     * @param topvisionProperties properties of the application
     * @return the Swagger Springfox configuration
     */
    @Bean
    public Docket swaggerSpringfoxDocket(TopvisionProperties topvisionProperties) {
        log.debug("Starting Swagger");
        StopWatch watch = new StopWatch();
        watch.start();
        Contact contact = new Contact(
                topvisionProperties.getSwagger().getContactName(),
                topvisionProperties.getSwagger().getContactUrl(),
                topvisionProperties.getSwagger().getContactEmail());

        ApiInfo apiInfo = new ApiInfo(
                topvisionProperties.getSwagger().getTitle(),
                topvisionProperties.getSwagger().getDescription(),
                topvisionProperties.getSwagger().getVersion(),
                topvisionProperties.getSwagger().getTermsOfServiceUrl(),
                contact,
                topvisionProperties.getSwagger().getLicense(),
                topvisionProperties.getSwagger().getLicenseUrl());

        // 设置全局参数
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        parameterBuilder
                .name("Authorization")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .description("授权信息：bearer token")
                .required(false)
                .build();

        ParameterBuilder ajaxParameterBuilder = new ParameterBuilder();
        ajaxParameterBuilder
                .name("X-Requested-With")
                .defaultValue("XMLHttpRequest")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .description("ajax请求，默认值：XMLHttpRequest")
                .required(false)
                .build();

        List<Parameter> parameters = new ArrayList<>();
        parameters.add(parameterBuilder.build());
        parameters.add(ajaxParameterBuilder.build());

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .forCodeGeneration(true)
                .directModelSubstitute(java.nio.ByteBuffer.class, String.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .globalOperationParameters(parameters)
                .select()
                .paths(PathSelectors.regex(topvisionProperties.getSwagger().getDefaultIncludePattern()))
                .build();
        watch.stop();
        log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
        return docket;
    }
}
